import React from 'react';
import { Card, Statistic, Button, Space, Table, Tag, Input, DatePicker, Select, Modal, Form, InputNumber, message } from 'antd';
import { DollarCircleOutlined, PlusOutlined, DownloadOutlined, SwapOutlined, FileTextOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;

// 模拟交易数据
const mockTransactions = Array.from({ length: 42 }).map((_, i) => {
  const types = ['充值', '提现', '消费', '退款', '结算'];
  const statuses = ['已完成', '处理中', '已关闭'];
  const type = types[i % types.length];
  const status = statuses[i % statuses.length];
  const amount = ((i + 1) * (i % 3 === 0 ? 12.5 : 8.8)).toFixed(2);
  return {
    id: `TX${20240000 + i}`,
    type,
    status,
    amount: Number(amount),
    time: dayjs().subtract(i, 'day').format('YYYY-MM-DD HH:mm'),
    orderNo: `ORD-${String(i).padStart(4, '0')}`,
    remark: `${type}示例记录${i}`,
  };
});

export default function WalletAccount() {
  const [balance, setBalance] = React.useState(5231.76);
  const [frozen, setFrozen] = React.useState(320.00);
  const [incomeTotal, setIncomeTotal] = React.useState(18234.98);
  const [expenseTotal, setExpenseTotal] = React.useState(13021.13);

  const [keyword, setKeyword] = React.useState('');
  const [dateRange, setDateRange] = React.useState([]);
  const [type, setType] = React.useState('all');
  const [status, setStatus] = React.useState('all');

  const [openRecharge, setOpenRecharge] = React.useState(false);
  const [openWithdraw, setOpenWithdraw] = React.useState(false);
  const [openInvoice, setOpenInvoice] = React.useState(false);

  const [formRecharge] = Form.useForm();
  const [formWithdraw] = Form.useForm();
  const [formInvoice] = Form.useForm();

  const columns = [
    { title: '交易号', dataIndex: 'id', width: 160 },
    { title: '类型', dataIndex: 'type', width: 90, render: (t) => <Tag color={t === '充值' ? 'green' : t === '提现' ? 'orange' : t === '消费' ? 'blue' : t === '退款' ? 'cyan' : 'purple'}>{t}</Tag> },
    { title: '金额(¥)', dataIndex: 'amount', width: 110, sorter: (a,b)=> a.amount - b.amount, render: (v)=> <span style={{ fontWeight: 600 }}>{v.toFixed(2)}</span> },
    { title: '状态', dataIndex: 'status', width: 100, render: (s)=> <Tag color={s === '已完成' ? 'green' : s === '处理中' ? 'gold' : 'red'}>{s}</Tag> },
    { title: '时间', dataIndex: 'time', width: 180, sorter: (a,b)=> dayjs(a.time).valueOf() - dayjs(b.time).valueOf() },
    { title: '关联订单', dataIndex: 'orderNo', width: 140 },
    { title: '备注', dataIndex: 'remark' },
  ];

  const filtered = React.useMemo(() => {
    return mockTransactions.filter(t => {
      const matchKW = keyword ? (t.id.includes(keyword) || t.orderNo.includes(keyword) || t.remark.includes(keyword)) : true;
      const matchType = type === 'all' ? true : t.type === type;
      const matchStatus = status === 'all' ? true : t.status === status;
      const matchDate = dateRange && dateRange.length === 2 ? (dayjs(t.time).isAfter(dateRange[0]) && dayjs(t.time).isBefore(dateRange[1])) : true;
      return matchKW && matchType && matchStatus && matchDate;
    });
  }, [keyword, type, status, dateRange]);

  return (
    <div>
      {/* 顶部概览 */}
      <Space direction="horizontal" size={16} style={{ width: '100%', marginBottom: 16 }}>
        <Card style={{ flex: 1 }}>
          <Statistic title="账户余额" prefix={<DollarCircleOutlined />} value={balance} precision={2} valueStyle={{ color: '#52c41a' }} />
        </Card>
        <Card style={{ flex: 1 }}>
          <Statistic title="冻结金额" prefix={<DollarCircleOutlined />} value={frozen} precision={2} valueStyle={{ color: '#fa8c16' }} />
        </Card>
        <Card style={{ flex: 1 }}>
          <Statistic title="累计收入" prefix={<DownloadOutlined />} value={incomeTotal} precision={2} valueStyle={{ color: '#389e0d' }} />
        </Card>
        <Card style={{ flex: 1 }}>
          <Statistic title="累计支出" prefix={<SwapOutlined />} value={expenseTotal} precision={2} valueStyle={{ color: '#cf1322' }} />
        </Card>
      </Space>

      {/* 操作栏 */}
      <Card variant="borderless" styles={{ body: { paddingTop: 8, paddingBottom: 8 } }}>
        <Space wrap>
          <Button type="primary" icon={<PlusOutlined />} onClick={()=> setOpenRecharge(true)}>充值</Button>
          <Button icon={<SwapOutlined />} onClick={()=> setOpenWithdraw(true)}>提现</Button>
          <Button icon={<FileTextOutlined />} onClick={()=> setOpenInvoice(true)}>开票</Button>
          <Input.Search allowClear placeholder="交易号/订单号/备注" style={{ width: 260 }} onSearch={(v)=> setKeyword(v)} />
          <RangePicker onChange={(v)=> setDateRange(v)} />
          <Select value={type} style={{ width: 120 }} onChange={(v)=> setType(v)} options={[
            { value: 'all', label: '全部类型' },
            { value: '充值', label: '充值' },
            { value: '提现', label: '提现' },
            { value: '消费', label: '消费' },
            { value: '退款', label: '退款' },
            { value: '结算', label: '结算' },
          ]} />
          <Select value={status} style={{ width: 120 }} onChange={(v)=> setStatus(v)} options={[
            { value: 'all', label: '全部状态' },
            { value: '已完成', label: '已完成' },
            { value: '处理中', label: '处理中' },
            { value: '已关闭', label: '已关闭' },
          ]} />
          <Button onClick={()=> { setKeyword(''); setDateRange([]); setType('all'); setStatus('all'); }}>重置</Button>
        </Space>
      </Card>

      {/* 交易明细 */}
      <Card title="交易明细" variant="borderless" styles={{ body: { paddingTop: 8 } }}>
        <Table
          rowKey={(r)=> r.id}
          dataSource={filtered}
          columns={columns}
          pagination={{ pageSize: 10 }}
        />
      </Card>

      {/* 充值弹窗 */}
      <Modal title="账户充值" open={openRecharge} onOk={()=>{
          formRecharge.validateFields().then(values => {
            setOpenRecharge(false);
            const add = Number(values.amount || 0);
            setBalance(b => b + add);
            message.success(`充值成功：¥${add.toFixed(2)}（示例）`);
          });
        }} onCancel={()=> setOpenRecharge(false)}>
        <Form form={formRecharge} layout="vertical" initialValues={{ amount: 100, method: '支付宝' }}>
          <Form.Item name="amount" label="金额(¥)" rules={[{ required: true, message: '请输入充值金额' }]}>
            <InputNumber min={1} precision={2} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="method" label="支付方式" rules={[{ required: true }]}>
            <Select options={[{ value: '支付宝', label: '支付宝' }, { value: '微信', label: '微信' }, { value: '银行卡', label: '银行卡' }]} />
          </Form.Item>
          <Form.Item name="remark" label="备注">
            <Input.TextArea rows={3} placeholder="可填写备注说明（示例）" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 提现弹窗 */}
      <Modal title="账户提现" open={openWithdraw} onOk={()=>{
          formWithdraw.validateFields().then(values => {
            const amount = Number(values.amount || 0);
            if (amount > balance) {
              message.error('提现金额不能超过账户余额');
              return;
            }
            setOpenWithdraw(false);
            setBalance(b => b - amount);
            message.success(`提现申请已提交：¥${amount.toFixed(2)}（示例）`);
          });
        }} onCancel={()=> setOpenWithdraw(false)}>
        <Form form={formWithdraw} layout="vertical" initialValues={{ amount: 100, channel: '银行卡' }}>
          <Form.Item name="amount" label="金额(¥)" rules={[{ required: true, message: '请输入提现金额' }]}>
            <InputNumber min={1} precision={2} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="channel" label="收款渠道" rules={[{ required: true }]}>
            <Select options={[{ value: '银行卡', label: '银行卡' }, { value: '支付宝', label: '支付宝' }, { value: '微信', label: '微信' }]} />
          </Form.Item>
          <Form.Item name="account" label="收款账号" rules={[{ required: true, message: '请输入账号' }]}>
            <Input placeholder="示例：6222 **** **** 1234" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 开票弹窗 */}
      <Modal title="申请开票" open={openInvoice} onOk={()=>{
          formInvoice.validateFields().then(values => {
            setOpenInvoice(false);
            message.success(`开票申请已提交（示例）：抬头 ${values.title}`);
          });
        }} onCancel={()=> setOpenInvoice(false)}>
        <Form form={formInvoice} layout="vertical" initialValues={{ title: '示例公司', taxId: '1234567890', amount: 100 }}>
          <Form.Item name="title" label="发票抬头" rules={[{ required: true, message: '请输入发票抬头' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="taxId" label="纳税人识别号" rules={[{ required: true, message: '请输入纳税人识别号' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="amount" label="开票金额(¥)" rules={[{ required: true }]}>
            <InputNumber min={1} precision={2} style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}